package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestProductorAndConsumerForLock {
    public static void main(String[] args) {
        Market1 market = new Market1();
        new Thread(new Productor1(market), "生产者1").start();
        new Thread(new Productor1(market), "生产者2").start();
        new Thread(new Consumer1(market), "消费者").start();
    }
}


class Market1 {
    int product;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void get() {
        lock.lock();
        try {
            while (product >= 10) {
                System.out.println("商品已满！");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName() + ",生产了商品:" + ++product);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

    public void send() {
        lock.lock();
        try {
            while (product <= 0) {
                System.out.println("商品已卖完！");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName() + ",消费了商品:" + --product);
            condition.signal();
        } finally {
            lock.unlock();
        }

    }
}

class Productor1 implements Runnable {
    Market1 market;

    public Productor1(Market1 market) {
        this.market = market;
    }

    @Override
    public void run() {
//        for (int i = 0; i < 20; i++) {
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            market.get();
        }
    }
}

class Consumer1 implements Runnable {
    Market1 market;

    public Consumer1(Market1 market) {
        this.market = market;
    }

    @Override
    public void run() {
//        for (int i = 0; i < 20; i++) {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            market.send();
        }
    }
}